/*
design and write by wuweiwei(邬畏畏) date: 2018.4
www.github.com/flybirdsoft
www.flybirdsoft.com/wing
www.flybirdsoftcom/wui
www.cnblogs.com/wsoft

说明：异步加载JavaScript文件,并按照顺序加载的顺序执行
*/
window.Module = {
	ingress : function(){}, /*通过require()方法重设*/
	callback : [],
	cache : [],
	headElement : document.getElementsByTagName("head")[0],
	exports:{},
	import:function(url,_name){
		/*
		url is 可选项
		*/
		var name;
		if(arguments.length==1)
		{
			name = url;
			return this.exports[name];
		}
		else if(arguments.length==2)
		{
			name = _name;
			return this.LoadOne(url,name);
		}
	},
	/*接口方法*/
	load : function(urls,callback){
		/*urls is array*/
		var headElement = this.headElement;
		var len , i , js;
		len = urls.length;
		this.urls = urls;
		this.index = 0;
		this.cache = [];
		this.asyncLoad(this.urls[this.index],callback);
	},
	asyncLoad : function(url,callback){
		var i;
		var js;
		var th = this;
		js = document.createElement("script");
		js.type = "text/javascript";
		js.src = url;
		if(this.index>=this.urls.length)
		{
			for(i=0;i<this.callback.length;i++)
			{
				this.callback[i]();
			}
			callback&&callback();
			this.ingress();
			return;
		}
		js.onload = js.onreadystatechange = function() {
			if(window.navigator.userAgent.indexOf("MSIE") > 0)
			{
				if(js.readyState == "loaded" || js.readyState == "complete")
				{
					th.cache.push(th.urls[th.index]);
					th.asyncLoad(th.urls[++th.index] , callback);
				}
			}
			else
			{
				th.cache.push(th.urls[th.index]);
				th.asyncLoad(th.urls[++th.index] , callback);
			}
		}
		this.headElement.appendChild(js);
	},
	LoadOne : function(url,name){
		var js;
		var th = this;
		var i , cache = this.cache , len = cache.length;
		var jsText = "";

		for(i=0;i<len;i++)
		{
			if(url==cache[i])
			{
				return th.exports[name];
			}
		}
		
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function(){
			jsText += xmlhttp.responseText
		}
		xmlhttp.open("GET",url,false);
		xmlhttp.send(null);
		js = document.createElement("script");
		js.type = "text/javascript";
		js.innerHTML = jsText;
		this.headElement.appendChild(js);
		this.cache.push(url);
		return th.exports[name];
	},

	define : function(f){
		console.log(this.callback);
		this.callback.push(f);
	},
	require : function(f){
		this.ingress = f;
	}
};

/*
API:

导出模块:
XX.js 里使用如下方式
Module.exports.xx = {}
Module.exports.xx = function(){}

加载JS(方式一):
var js = ["js/1.js","js/2.js","js/3.js"];
Module.load(js,function(){
	var Man = Module.import("Man");
	var Children = Module.import("Children");
	Man.show();
	Children.show();	
}); //异步载入js,而且按照顺序执行

Module.require(function(){});

加载JS(方式二):
var js = ["js/1.js","js/2.js","js/3.js"];
Module.load(js); 
Module.require(function(){
	var app = Module.import("app");
	app.show();
});

同步导入模块:
Module.import("url",moduleName);
var app = Module.import("js/1.js","app");
alert(app.version);

*/

